<!DOCTYPE html>
<html lang="zh-CN">
    
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>单片机监控面板</title>
    <!-- 引入Bootstrap CSS -->
    <script type="text/javascript">
        function init() {
            refresh();
        }

        async function refresh() {
            console.log('开始刷新数据');
            try {
                const url = "http://localhost:8080/api/data"; 
                const post_req = {
                    "type": 1,
                    "limit": "all"
                };
                const response = await fetch(url, {
                    method: "POST",
                    headers: {
                        "Content-Type": "application/json"
                    },
                    body: JSON.stringify(post_req)
                });

                if (!response.ok) {
                    throw new Error(`请求失败，状态码: ${response.status}`);
                }

                const info = await response.json() || {};
                console.log('刷新数据成功:', info);

                // 定义映射表
                const dataMapping = {
                    temperature: { id: 'temperature', formatter: value => value || 'N/A' },
                    humidity: { id: 'humidity', formatter: value => value || 'N/A' },
                    light: { id: 'light', formatter: value => value || 'N/A' },
                    fire: { id: 'fire', formatter: value => value === 1 ? '检测到火焰' : value === 0 ? '正常' : 'N/A' },
                    led: { id: 'ledStatus', formatter: value => value === 1 ? '开启' : value === 0 ? '关闭' : 'N/A' },
                    fan: { id: 'fan', formatter: value => value === 1 ? '开启' : value === 0 ? '关闭' : 'N/A' },
                    smoke: { id: 'smoke', formatter: value => typeof value === 'number' ? value.toFixed(2) : 'N/A' },
                    window_switch: { id: 'open', formatter: value => value === 1 ? '已开窗' : value === 0 ? '已关窗' : 'N/A' },
                    cooling: { id: 'coolingStatus', formatter: value => value === 1 ? '开启' : value === 0 ? '关闭' : 'N/A' },
                    heating: { id: 'heatingStatus', formatter: value => value === 1 ? '开启' : value === 0 ? '关闭' : 'N/A' },
                    // 新增马达状态映射
                    motor: { id: 'motorStatus', formatter: value => value === 1 ? '开启' : value === 0 ? '关闭' : 'N/A' },
                    // 新增蜂鸣器状态映射
                    buzzer: { id: 'buzzerStatus', formatter: value => value === 1 ? '开启' : value === 0 ? '关闭' : 'N/A' }
                };

                // 更新页面数据
                Object.entries(dataMapping).forEach(([key, { id, formatter }]) => {
                    const element = document.getElementById(id);
                    if (element) {
                        try {
                            element.textContent = formatter(info[key]);
                        } catch (error) {
                            console.error(`更新 ${id} 数据出错:`, error);
                            element.textContent = 'N/A';
                        }
                    }
                });
            } catch (error) {
                console.error('刷新数据出错:', error);
            }
        }
    </script>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        .data-panel {
            margin-top: 20px;
            padding: 20px;
            border: 1px solid #ddd;
            border-radius: 5px;
            background-color: #f9f9f9;
        }
        .data-item {
            margin-bottom: 20px;
            padding: 15px;
            background-color: white;
            border-radius: 5px;
            border: 1px solid #eee;
        }
        .data-label {
            font-weight: bold;
            margin-right: 10px;
        }
        .btn-on {
            background-color: #28a745;
            color: white;
        }
        .btn-off {
            background-color: #dc3545;
            color: white;
        }
        .btn {
            margin-top: 10px;
        }
    </style>
</head>
<body onload="init()">
    <div class="container">
        <h1 class="mt-4">单片机监控面板</h1>

        <div class="data-panel">
            <h2>实时数据与设备控制</h2>
            <div id="sensorData">
                <!-- 温度数据项 -->
                <div class="data-item">
                    <span class="data-label">温度:</span>
                    <span id="temperature">--</span> °C
                </div>
                <!-- 湿度数据项 -->
                <div class="data-item">
                    <span class="data-label">湿度:</span>
                    <span id="humidity">--</span> %
                </div>
                <!-- 光照数据项 -->
                <div class="data-item">
                    <span class="data-label">光照:</span>
                    <span id="light">--</span> lx
                </div>
                <!-- 火焰传感器数据项 -->
                <div class="data-item">
                    <span class="data-label">火焰传感器:</span>
                    <span id="fire">--</span>
                </div>
                <!-- LED 数据项及控制按钮 -->
                <div class="data-item">
                    <span class="data-label">LED情况:</span>
                    <span id="ledStatus">--</span>
                    <button id="led" class="btn btn-off" onclick="toggleLED()">LED 关闭</button>
                </div>
                <!-- 风扇数据项及控制按钮 -->
                <div class="data-item">
                    <span class="data-label">风扇情况:</span>
                    <span id="fan">--</span>
                    <button id="fanBtn" class="btn btn-off" onclick="toggleFan()">风扇 关闭</button>
                </div>
                <!-- 制冷数据项及控制按钮 -->
                <div class="data-item">
                    <span class="data-label">制冷状态:</span>
                    <span id="coolingStatus">--</span>
                    <button id="cooling" class="btn btn-off" onclick="toggleCooling()">制冷 关闭</button>
                </div>
                <!-- 制热数据项及控制按钮 -->
                <div class="data-item">
                    <span class="data-label">制热状态:</span>
                    <span id="heatingStatus">--</span>
                    <button id="heating" class="btn btn-off" onclick="toggleHeating()">制热 关闭</button>
                </div>
                <!-- 马达数据项及控制按钮 -->
                <div class="data-item">
                    <span class="data-label">马达状态:</span>
                    <span id="motorStatus">--</span>
                    <button id="motor" class="btn btn-off" onclick="toggleMotor()">马达 关闭</button>
                </div>
                <!-- 蜂鸣器数据项及控制按钮 -->
                <div class="data-item">
                    <span class="data-label">蜂鸣器状态:</span>
                    <span id="buzzerStatus">--</span>
                    <button id="buzzer" class="btn btn-off" onclick="toggleBuzzer()">蜂鸣器 关闭</button>
                </div>
                <!-- 烟雾传感器数据项 -->
                <div class="data-item">
                    <span class="data-label">烟雾传感器:</span>
                    <span id="smoke">--</span>
                </div>
                <!-- 开窗状态数据项及控制按钮 -->
                <div class="data-item">
                    <span class="data-label">开窗状态:</span>
                    <span id="open">--</span>
                    <button id="relay" class="btn btn-off" onclick="toggleRelay()">窗户 关闭</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 引入Bootstrap JS和依赖 -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // 定义设备 key 映射
        const deviceKeyMap = {
            "led": 305, // 假设合并后的 LED key
            "fan": 306,
            "relay": 102,
            "cooling": null, // 假设无对应 key，需按需修改
            "heating": null, // 假设无对应 key，需按需修改
            "motor": null, // 需根据 node.json 配置修改
            "buzzer": null // 需根据 node.json 配置修改
        };

        // 向单片机发送指令
        async function sendCommand(device, state) {
            const key = deviceKeyMap[device];
            if (key === null || key === undefined) {
                console.error('未找到设备对应的 key 值');
                return;
            }
            console.log(`发送指令: 设备 ${device} (Key: ${key}) 状态 ${state}`);
            try {
                const url = "http://localhost:8080/api/control"; 
                console.log('请求地址:', url);
                const requestBody = { key, state };
                console.log('请求体:', requestBody);
                const response = await fetch(url, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(requestBody),
                });

                if (!response.ok) {
                    const errorText = await response.text();
                    throw new Error(`请求失败，状态码: ${response.status}, 错误信息: ${errorText}`);
                }

                const data = await response.json();
                console.log(`指令响应: ${data.message}`);
            } catch (error) {
                console.error('发送指令出错:', error);
                if (error instanceof TypeError) {
                    console.error('可能是 CORS 问题，请检查服务器配置');
                }
                alert(`发送指令出错: ${error.message}`);
            }
        }

        async function refresh() {
            console.log('开始刷新数据');
            try {
                const url = "http://localhost:8080/api/data"; 
                const post_req = {
                    "type": 1,
                    "limit": "all"
                };
                const response = await fetch(url, {
                    method: "POST",
                    headers: {
                        "Content-Type": "application/json"
                    },
                    body: JSON.stringify(post_req)
                });

                if (!response.ok) {
                    throw new Error(`请求失败，状态码: ${response.status}`);
                }

                const info = await response.json() || {};
                console.log('刷新数据成功:', info);

                // 更新页面数据
                document.getElementById('temperature').textContent = info.temperature;
                document.getElementById('humidity').textContent = info.humidity;
                document.getElementById('light').textContent = info.light;
                document.getElementById('fire').textContent = info.fire === 1 ? '检测到火焰' : '正常';
                document.getElementById('ledStatus').textContent = info.led.toFixed(2);
                document.getElementById('fan').textContent = info.fan.toFixed(2);
                document.getElementById('smoke').textContent = info.smoke.toFixed(2);
                document.getElementById('open').textContent = info['window_switch'] === 1 ? '已开窗' : '已关窗';
            } catch (error) {
                console.error('刷新数据出错:', error);
            }
        }

        // 控制LED状态
        function toggleLED() {
            const btn = document.getElementById('led');
            const isOn = btn.classList.contains('btn-on');
            const newState = isOn ? 0 : 1;
            console.log(`按钮操作: LED 切换到 ${newState === 1 ? '开启' : '关闭'} 状态`);

            if (isOn) {
                btn.classList.remove('btn-on');
                btn.classList.add('btn-off');
                btn.textContent = 'LED 关闭';
                sendCommand('led', 0);
            } else {
                btn.classList.remove('btn-off');
                btn.classList.add('btn-on');
                btn.textContent = 'LED 开启';
                sendCommand('led', 1);
            }
            refresh(); // 更新状态显示
        }

        // 控制风扇状态
        function toggleFan() {
            const btn = document.getElementById('fanBtn');
            const isOn = btn.classList.contains('btn-on');

            if (isOn) {
                btn.classList.remove('btn-on');
                btn.classList.add('btn-off');
                btn.textContent = '风扇 关闭';
                sendCommand('fan', 0);
            } else {
                btn.classList.remove('btn-off');
                btn.classList.add('btn-on');
                btn.textContent = '风扇 开启';
                sendCommand('fan', 1);
            }
            refresh();
        }

        // 控制窗户状态
        function toggleRelay() {
            const btn = document.getElementById('relay');
            const isOn = btn.classList.contains('btn-on');

            if (isOn) {
                btn.classList.remove('btn-on');
                btn.classList.add('btn-off');
                btn.textContent = '窗户 关闭';
                sendCommand('relay', 0);
            } else {
                btn.classList.remove('btn-off');
                btn.classList.add('btn-on');
                btn.textContent = '窗户 开启';
                sendCommand('relay', 1);
            }
            refresh();
        }

        // 制冷开关
        function toggleCooling() {
            const btn = document.getElementById('cooling');
            const isOn = btn.classList.contains('btn-on');

            if (isOn) {
                btn.classList.remove('btn-on');
                btn.classList.add('btn-off');
                btn.textContent = '制冷 关闭';
                sendCommand('cooling', 0);
            } else {
                btn.classList.remove('btn-off');
                btn.classList.add('btn-on');
                btn.textContent = '制冷 开启';
                sendCommand('cooling', 1);
            }
            refresh();
        }

        // 制热开关
        function toggleHeating() {
            const btn = document.getElementById('heating');
            const isOn = btn.classList.contains('btn-on');

            if (isOn) {
                btn.classList.remove('btn-on');
                btn.classList.add('btn-off');
                btn.textContent = '制热 关闭';
                sendCommand('heating', 0);
            } else {
                btn.classList.remove('btn-off');
                btn.classList.add('btn-on');
                btn.textContent = '制热 开启';
                sendCommand('heating', 1);
            }
            refresh();
        }

        // 控制马达状态
        function toggleMotor() {
            const btn = document.getElementById('motor');
            const isOn = btn.classList.contains('btn-on');

            if (isOn) {
                btn.classList.remove('btn-on');
                btn.classList.add('btn-off');
                // 修改按钮文本
                btn.textContent = '马达 关闭';
                sendCommand('motor', 0);
            } else {
                btn.classList.remove('btn-off');
                btn.classList.add('btn-on');
                // 修改按钮文本
                btn.textContent = '马达 开启';
                sendCommand('motor', 1);
            }
            refresh(); // 更新状态显示
        }

        // 控制蜂鸣器状态
        function toggleBuzzer() {
            const btn = document.getElementById('buzzer');
            const isOn = btn.classList.contains('btn-on');

            if (isOn) {
                btn.classList.remove('btn-on');
                btn.classList.add('btn-off');
                // 修改按钮文本
                btn.textContent = '蜂鸣器 关闭';
                sendCommand('buzzer', 0);
            } else {
                btn.classList.remove('btn-off');
                btn.classList.add('btn-on');
                // 修改按钮文本
                btn.textContent = '蜂鸣器 开启';
                sendCommand('buzzer', 1);
            }
            refresh(); // 更新状态显示
        }

        // 定时获取数据
        setInterval(refresh, 2000);
        // 初始加载
        refresh();
    </script>
</body>
</html>
